package com.xiangyang.pos.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.xiangyang.pos.R;
import com.xiangyang.pos.bean.BLEItem;
import com.xiangyang.pos.bean.BLEListAdapter;
import com.xiangyang.pos.bean.Conts;
import com.xiangyang.pos.utils.SharedUtils;
import com.xiangyang.pos.utils.ToastUtils;

import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.UiExecute;
import net.posprinter.service.PosprinterService;
import net.posprinter.utils.DataForSendToPrinterPos58;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

/**
 * ==========================================================
 * <p>
 * 版 权： 向阳三合道科技 安卓开发团队 版权所有(c) 2017/9/11
 * <p>
 * 作 者： 段雪彬
 * <p>
 * 版 本： 1.0
 * <p>
 * 创建日期：2017/9/11 14:49
 * <p>
 * 描 述：
 * 打印机逻辑》》》
 * * 先连接，连接失败
 * * 显示对话框蓝牙列表
 * * 在连接
 * <p>
 * 连接成功就打印
 * <p>
 * 修订历史：
 * <p>
 * ==========================================================
 */

public class DealDoneActivity extends Activity {

    private Button bSure;
    private ImageView ivDy;
    private boolean isDy=true;
    public static IMyBinder binder;//IMyBinder接口，所有可供调用的连接和发送数据的方法都封装在这个接口内
    //bindService的参数conn
    ServiceConnection conn ;
    //连接状态，通过这个状态我们可以做一些事情
    private boolean isConnect;

    private ArrayList<BLEItem> bleList_finded = new ArrayList<>();
    private BluetoothAdapter mBlueadapter;
    private BLEListAdapter bleListAdapter;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            Intent intent = new Intent(DealDoneActivity.this, FirstActivity.class);
            startActivity(intent);
            return false;
        }

    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deal_done);
       /* //绑定service，获取ImyBinder对象
        Intent intent = new Intent(this, PosprinterService.class);
        startService(intent);
        bindService(intent, conn, BIND_AUTO_CREATE);
        //注意，绑定服务后不能马上操作打印机相关的API，否则会报空指针。bindService*/

        initView();
        setMyClick();
    }

    private void initView() {
        bSure = findViewById(R.id.b_sure);
        ivDy=findViewById(R.id.iv_dy);

        isDy=SharedUtils.getBooleanPrefs(this,"isDy",true);
        if(!isDy){
            ivDy.setImageResource(R.mipmap.dy_x);
        }
    }

    private void setMyClick() {
        bSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(isDy){

                    conn = new ServiceConnection() {

                        @Override
                        public void onServiceDisconnected(ComponentName name) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onServiceConnected(ComponentName name, IBinder service) {
                            // TODO Auto-generated method stub
                            //绑定成功
                            binder = (IMyBinder) service;
                        }
                    };

                    //绑定service，获取ImyBinder对象
                    Intent intent = new Intent(DealDoneActivity.this, PosprinterService.class);
                    startService(intent);
                    bindService(intent, conn, BIND_AUTO_CREATE);
                    //注意，绑定服务后不能马上操作打印机相关的API，否则会报空指针。bindService

                    handler.sendEmptyMessageDelayed(1001,500);
//                    connectBLE();//检测蓝牙连接状态
                }else {
                    Intent intent = new Intent(DealDoneActivity.this, FirstActivity.class);
                    startActivity(intent);
                }
//                getHttp();
            }
        });

        ivDy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isDy=!isDy;
                if(isDy){
                    ivDy.setImageResource(R.mipmap.dy);
                    SharedUtils.setBooleanPrefs(DealDoneActivity.this,"isDy",isDy);
                    Toast.makeText(DealDoneActivity.this,"已开启打印",Toast.LENGTH_SHORT).show();
                }else {
                    ivDy.setImageResource(R.mipmap.dy_x);
                    Toast.makeText(DealDoneActivity.this,"已关闭打印",Toast.LENGTH_SHORT).show();
                }
                SharedUtils.setBooleanPrefs(DealDoneActivity.this,"isDy",isDy);
            }
        });

    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1001){
                connectBLE();//检测蓝牙连接状态
            }
        }
    };

   /* private void getHttp() {
        String apiToken = SharedUtils.getStringPrefs(this, "apiToken", "");
        final String DONE_URL = AppConstant.POS_URL + "/Pay/An/PayStream/u=" + apiToken;

        Logger.e("xxxx", "DONE_URL = " + DONE_URL);
        HttpClient httpClient = new HttpClient();
        httpClient.post(DONE_URL, getDealData(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                if (!result.equals("Error")) {
                    Logger.e("xxxx", "result = " + result);
                    Gson gson = new Gson();
                    HttpBean bean = gson.fromJson(result, HttpBean.class);
                    if (bean != null) {
                        if (bean.getStatus() == 1) {
//                            处理成功，正在打印凭条
//                            connectBLE();//检测蓝牙连接状态
                            if(!isDy){
                                mHandler.sendEmptyMessage(0);
                            }
                            Toast.makeText(DealDoneActivity.this, "交易数据提交成功", Toast.LENGTH_SHORT).show();

                        } else {
                            Logger.e("xxx", "DealDoneActivity  msg    " + bean.getMsg());
                            Toast.makeText(DealDoneActivity.this, "交易数据提交失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(DealDoneActivity.this, "为空", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(DealDoneActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    //    提交交易数据
    private RequestParameters getDealData() {

        String emp_id = SharedUtils.getStringPrefs(DealDoneActivity.this, "account", "");
        String phone_num = (String) SharedUtils.getStringPrefs(DealDoneActivity.this, "user_phone", "");
        String userId = (String) SharedUtils.getStringPrefs(DealDoneActivity.this, "userId", "");
        int truepay = (int) SharedUtils.getIntPrefs(DealDoneActivity.this, "all_money", -1);
        String pay_way = (String) SharedUtils.getStringPrefs(DealDoneActivity.this, "pmt_tag", "");
        String goodscode = (String) SharedUtils.getStringPrefs(DealDoneActivity.this, "list_code", "");
        String payNum = (String) SharedUtils.getStringPrefs(DealDoneActivity.this, "out_on", "");

        Logger.e("xxx", "payNum = " + payNum);

        RequestParameters parameters = new RequestParameters();
        parameters.put("emp_id", emp_id);//交易员工
        parameters.put("phone_num", phone_num);//交易用户
        parameters.put("userId", userId);
        parameters.put("truepay", "" + truepay / 100.0);//交易金额
        parameters.put("pay_way", pay_way);//支付方式
        parameters.put("goodscode", goodscode);//商品条码集合
        parameters.put("payNum", payNum);//交易流水号

        Gson gson = new Gson();
        String str = gson.toJson(parameters);

        Logger.e("xxxxxxxxx", str);

        return parameters;

    }*/

  /*  @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        String pay_way = SharedUtils.getStringPrefs(DealDoneActivity.this, "pmt_tag", "");
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (!pay_way.equals("Cash")) {               //true
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false);
                builder.setTitle("警告");
                builder.setMessage("该交易不是现金交易，且已支付成功，因此不能点击返回。");
                builder.setPositiveButton("确定", null);
                builder.show();
            }

            *//*AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("不能点击返回");
            builder.setPositiveButton("确定", null);
            builder.show();*//*

            isDy=false;

        }
        return super.onKeyDown(keyCode, event);
    }*/

    //======================================================以下打印相关代码

    /**
     * 检测蓝牙连接状态
     *
     * @return
     */
    private void connectBLE() {
        // TODO Auto-generated method stub
        mBlueadapter = BluetoothAdapter.getDefaultAdapter();
        //确认开启蓝牙
        if (!mBlueadapter.isEnabled()) {
            //请求用户开启
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, Conts.ENABLE_BLUETOOTH);
        } else {
            //蓝牙已开启，尝试连接
            sendble();
        }
    }

    public void sendble() {
        String blemac = SharedUtils.getStringPrefs(DealDoneActivity.this, "blemac", "DC:0D:30:24:35:34");
        //这里连接蓝牙是通过一串字符串地址，应该是固定的，我这里写死吧
        binder.connectBtPort(blemac, new UiExecute() {
            @Override
            public void onsucess() {
                // TODO Auto-generated method stub
                //连接成功后在UI线程中的执行
                isConnect = true;
                Toast.makeText(DealDoneActivity.this, getString(R.string.con_success), Toast.LENGTH_LONG).show();
                ToastUtils.showToast(DealDoneActivity.this, getString(R.string.con_success));
                try {
                    print();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //此处也可以开启读取打印机的数据
                //参数同样是一个实现的UiExecute接口对象
                //如果读的过程重出现异常，可以判断连接也发生异常，已经断开
                //这个读取的方法中，会一直在一条子线程中执行读取打印机发生的数据，
                //直到连接断开或异常才结束，并执行onfailed`
                binder.acceptdatafromprinter(new UiExecute() {

                    @Override
                    public void onsucess() {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onfailed() {
                        // TODO Auto-generated method stub
                        isConnect = false;
//                        Toast.makeText(DealDoneActivity.this, getString(R.string.con_has_discon), Toast.LENGTH_LONG).show();
                        ToastUtils.showToast(DealDoneActivity.this, getString(R.string.con_has_discon));
                    }
                });
            }

            @Override
            public void onfailed() {
                // TODO Auto-generated method stub
                //连接失败后在UI线程中的执行
                isConnect = false;
                Toast.makeText(DealDoneActivity.this, getString(R.string.con_failed), Toast.LENGTH_LONG).show();
                //btn0.setText("连接失败");
                showblueboothlist();
            }
        });
    }

    /**
     * 未连接成功，这里显示蓝牙对话框列表
     */
    private void showblueboothlist() {
        //判断蓝牙是否在扫描
        if (!mBlueadapter.isDiscovering()) {
            mBlueadapter.startDiscovery();
        }
        //BaseAdapter的实现类，显示列表数据
        bleListAdapter = new BLEListAdapter(DealDoneActivity.this, bleList_finded);
        //搜索已配对的蓝牙设备
        findAvalibleBLE();
        //显示已配对
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(DealDoneActivity.this);
        builder.setTitle("已配对的设备");
        builder.setSingleChoiceItems(bleListAdapter, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                BLEItem bleItem = bleList_finded.get(which);
                SharedUtils.setStringPrefs(DealDoneActivity.this, "blemac", bleItem.getMac());
                dialog.dismiss();
                Toast.makeText(DealDoneActivity.this, "正在再次尝试", Toast.LENGTH_SHORT).show();
                connectBLE();
            }
        });
//        builder.create().show();
        builder.show();
    }

    /**
     * 搜索已配对的蓝牙列表，里面注释的内容是暂时不用的，但不代表以后用不着。
     * adapter1 是显示蓝牙对话框列表中的BaseAdapter的实现类
     */
    private void findAvalibleBLE() {
        // TODO Auto-generated method stub
        //获取可配对蓝牙设备
        Set<BluetoothDevice> device = mBlueadapter.getBondedDevices();
        bleList_finded.clear();
        if (mBlueadapter != null && mBlueadapter.isDiscovering()) {
            bleListAdapter.notifyDataSetChanged();
        }
        if (device.size() > 0) {
            //存在已经配对过的蓝牙设备
            for (Iterator<BluetoothDevice> it = device.iterator(); it.hasNext(); ) {
                BluetoothDevice btd = it.next();
                bleList_finded.add(new BLEItem(btd.getName(), btd.getAddress()));
//                bleListAdapter.notifyDataSetChanged();
            }
        }
//        else{  //不存在已经配对过的蓝牙设备
//            bleList_finded.add("No can be matched to use bluetooth");
//            bleListAdapter.notifyDataSetChanged();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(binder!=null){
            binder.disconnectCurrentPort(new UiExecute() {

                @Override
                public void onsucess() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onfailed() {
                    // TODO Auto-generated method stub

                }
            });
            unbindService(conn);
        }


    }

    public void print() throws UnsupportedEncodingException {
        // TODO Auto-generated method stub
        //此处用binder里的另外一个发生数据的方法,同样，也要按照编程手册上的示例一样，先设置标签大小
        //如果数据处理较为复杂，请勿选择此方法
        //上面的发送方法的数据处理是在工作线程中完成的，不会阻塞UI线程

        String head = "消费凭条（POS）\n";
        String shop = "地  址:" + SharedUtils.getStringPrefs(DealDoneActivity.this, "address", "向阳网络") + "\n" + "收银员:" + SharedUtils.getStringPrefs(DealDoneActivity.this, "name", "向阳网络") + "\n" + "订单编号:" + SharedUtils.getStringPrefs(DealDoneActivity.this, "out_trade_no", "订单编号") + "\n";
        String content = SharedUtils.getStringPrefs(DealDoneActivity.this, "list_order", "");
        String bottom = "合计：￥" + SharedUtils.getIntPrefs(DealDoneActivity.this, "all_money", -1) / 100.0 + "\n"
                + "会员ID:" + SharedUtils.getStringPrefs(DealDoneActivity.this, "user_phone", "***********") + "\n\n\n\n";
        String total = head + shop + content + bottom;
        byte[] bytes = DataForSendToPrinterPos58.printAndFeedForward(10);
        byte[] tt = byteMerger(total.getBytes("gbk"), bytes);
        binder.write(tt, new UiExecute() {

            @Override
            public void onsucess() {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), getString(R.string.send_success), Toast.LENGTH_SHORT)
                        .show();
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void onfailed() {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), getString(R.string.send_failed), Toast.LENGTH_SHORT).show();
            }
        });
}

    /**
     * byte数组拼接
     */
    private byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
        byte[] byte_3 = new byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(DealDoneActivity.this, FirstActivity.class);
            startActivity(intent);
        }

        return super.onKeyDown(keyCode, event);
    }

}
